<template>
  <div class="edit-page-wrap">
    <Head title="版本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="150px"
          class="edit-form-wrap"
        >
          <el-form-item label="版本号" prop="version">
            <el-input
              v-model.trim="ruleForm.version"
              placeholder="请输入版本号"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="充电桩类型" prop="chargingPileType">
            <el-radio-group
              v-model="ruleForm.chargingPileType"
              v-for="(item, index) in optionsS.chargingPileTypeData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电桩功率" prop="powerChargingPile">
            <el-input
              v-model.trim="ruleForm.powerChargingPile"
              placeholder="请输入电桩功率"
              maxlength="9"
              clearable
            >
              <template #append>kW</template>
            </el-input>
          </el-form-item>
          <el-form-item label="升级包获取" prop="isAutoUpdate">
            <el-radio-group
              v-model="ruleForm.isAutoUpdate"
              v-for="(item, index) in IS_AUTOUPDATE"
              :key="index"
              @change="handleAutoUpdate"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="本地上传"
            prop="uploadFilePath"
            class="inline-form"
            v-if="ruleForm.isAutoUpdate && !optionsS.fileShow"
          >
            <el-upload
              ref="uploadRef"
              class="upload-xls"
              drag
              action="#"
              :auto-upload="true"
              :http-request="uploadFile"
              :on-remove="onRemove"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖至此处或点击此处上传
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="本地上传"
            prop="filePath"
            v-if="
              id &&
              ruleForm.isAutoUpdate &&
              optionsS.fileShow
            "
          >
            <div class="dispute-value">{{ ruleForm.filePath }}</div>
            <el-button
              class="dispute-upload"
              type="primary"
              plain
              v-btnAntiShake="onUpload"
            >
              重新上传
            </el-button>
          </el-form-item>
          <div v-if="!ruleForm.isAutoUpdate">
            <el-form-item label="FTP服务器地址" prop="ftpAddress">
              <el-input
                v-model.trim="ruleForm.ftpAddress"
                placeholder="请输入FTP服务器地址"
                maxlength="255"
                clearable
              />
            </el-form-item>
            <el-form-item label="FTP服务器端口" prop="ftpPort">
              <el-input
                v-model.trim="ruleForm.ftpPort"
                placeholder="请输入FTP服务器端口"
                maxlength="9"
                clearable
              />
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model.trim="ruleForm.userName"
                placeholder="请输入用户名"
                maxlength="50"
                clearable
              />
            </el-form-item>
            <el-form-item label="账号密码" prop="accountPassword">
              <el-input
                v-model.trim="ruleForm.accountPassword"
                placeholder="请输入账号密码"
                maxlength="30"
                clearable
              />
            </el-form-item>
            <el-form-item label="文件路径" prop="filePath">
              <el-input
                v-model.trim="ruleForm.filePath"
                placeholder="请输入文件路径"
                maxlength="255"
                clearable
              />
            </el-form-item>
          </div>
          <el-form-item label="执行控制" prop="executiveControl">
            <el-radio-group
              v-model="ruleForm.executiveControl"
              v-for="(item, index) in optionsS.executiveControlData"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="下载超时时间" prop="downloadTimeout">
            <el-input
              v-model.trim="ruleForm.downloadTimeout"
              placeholder="请输入下载超时时间"
              maxlength="2"
              clearable
            >
              <template #append>分钟</template>
            </el-input>
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import Head from '@/components/head/index.vue';
import {
  updateFtp,
  addFtp,
  getByIdFtp,
  ftpUpload,
} from '@/service/apis/config';
import { queryDicByParent } from '@/service/apis/api';
import { IS_NUM1, IS_INTEGER, IS_1To60 } from '@/utils/verify';
import { IS_AUTOUPDATE } from '@/utils/dictionaries';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();

let optionsS = reactive({
  chargingPileTypeData: [] as any,
  executiveControlData: [] as any,
  fileShow: true,
});

// 字典
queryDicByParent({ listDtos: ['chargingPileType', 'executiveControl'] }).then(
  (res: any) => {
    optionsS.chargingPileTypeData = res.chargingPileType;
    optionsS.executiveControlData = res.executiveControl;
  }
);

const checkFile = (rule: any, value: any, callback: any) => {
  if (value.length == 0) {
    callback(new Error('请上传文件'));
  }
  callback();
};

const handleAutoUpdate = (e:any)=>{
  ruleForm.isAutoUpdate = e
  ruleForm.ftpAddress = '';
  ruleForm.ftpPort = '';
  ruleForm.userName = '';
  ruleForm.accountPassword = '';
  ruleForm.filePath = '';
  ruleForm.uploadFilePath = '';
  optionsS.fileShow = false;
}

let ruleForm: any = reactive({
  id: '',
  version: '',
  chargingPileType: '',
  powerChargingPile: '',
  ftpAddress: '',
  ftpPort: '',
  userName: '',
  accountPassword: '',
  filePath: '',
  executiveControl: '',
  downloadTimeout: '',
  isAutoUpdate: false,
});

const rules = reactive<FormRules>({
  version: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
  chargingPileType: [
    { required: true, message: '请选择充电桩类型', trigger: 'change' },
  ],
  isAutoUpdate: [
    { required: true, message: '请选择升级包获取方式', trigger: 'change' },
  ],
  powerChargingPile: [
    { required: true, message: '请输入电桩功率', trigger: 'blur' },
    {
      pattern: IS_NUM1,
      message: '请输入数字或小数',
      trigger: 'blur',
    },
  ],
  ftpAddress: [
    { required: true, message: '请输入FTP服务器地址', trigger: 'blur' },
  ],
  ftpPort: [
    { required: true, message: '请输入FTP服务器端口', trigger: 'blur' },
    {
      pattern: IS_INTEGER,
      message: '请输入数字',
      trigger: 'blur',
    },
  ],
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  accountPassword: [
    { required: true, message: '请输入账号密码', trigger: 'blur' },
  ],
  filePath: [{ required: true, message: '请输入文件路径', trigger: 'blur' }],
  uploadFilePath: [
    { required: true, message: '请上传文件', trigger: 'change' },
    { validator: checkFile, trigger: 'change' },
  ],
  executiveControl: [
    { required: true, message: '请选择执行控制', trigger: 'change' },
  ],
  downloadTimeout: [
    { required: true, message: '请输入下载超时时间', trigger: 'blur' },
    {
      pattern: IS_1To60,
      message: '请输入1~60的正整数',
      trigger: 'blur',
    },
  ],
});

// 重新上传
const onUpload = () => {
  optionsS.fileShow = false;
};
// const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
//   return getFileType(rawFile, 'xlsx').then((fileType) => {
//     // 校验上传类型
//     if (!fileType) {
//       ElMessageBox.alert('请导入xlsx、xls格式的文件！', '提示', {
//         confirmButtonText: '确认',
//         type: 'warning',
//       });
//       return false;
//     }
//     return true;
//   });
// };
const onRemove: UploadProps['onRemove'] = () => {
  ruleForm.uploadFilePath = [];
};
const uploadFile = (data: any) => {
  return new Promise((resolve, reject) => {
    const uploadFilePath = [data!.file];
    const formData = new FormData();
    formData.append('file', uploadFilePath[0]);
    ftpUpload(formData).then((res: any) => {
      if (res) {
        ruleForm.uploadFilePath = res;
      } else {
        ruleForm.uploadFilePath = '';
        ruleFormRef?.value?.clearValidate('uploadFilePath');
      }
    });
  });
};

const handleExceed: UploadProps['onExceed'] = () => {
  ElMessageBox.alert('最多可以上传1个文件', '提示', {
    confirmButtonText: '确认',
    type: 'warning',
  });
};

// 返回
const back = () => {
  router.go(-1);
};

// 编辑回填数据
if (id) {
  getByIdFtp(id).then((res: any) => {
    for (const key in ruleForm) {
      if (res[key]) {
        ruleForm[key] = res[key];
      }
    }
    // ruleForm.uploadFilePath = ruleForm.filePath
    ruleForm.chargingPileType = String(res.chargingPileType);
    ruleForm.executiveControl = res.executiveControl
      ? res.executiveControl.toString()
      : '';
    console.log('ruleForm---', ruleForm);
  });
}

// 新增/修改提交
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value) return;
  try {
    await Promise.all([ruleFormRef.value.validate()]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  if (ruleForm.isAutoUpdate) {
    ruleForm.filePath = ruleForm.uploadFilePath;
  }
  console.log('ruleForm---', ruleForm);
  if (id) {
    ruleForm.id = id;
    updateFtp(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addFtp(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>
<style lang="scss">
.main-wrap .edit-page-wrap .edit-form-wrap .el-input {
  margin: 4px;
}
.dispute-upload {
  margin-left: 20px;
}
</style>